<?php

namespace app\api\controller;

use app\api\library\WechatPay;
use app\common\controller\Api;
use think\Db;
use WeChatPay\Crypto\AesGcm;
use WeChatPay\Crypto\Rsa;
use WeChatPay\Formatter;
use think\Log;

class Test extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    public function close()
    {
        $id = $this->request->param('id');
        \app\admin\model\Activity::where('id',$id)->update(['status'=>2]);
        $this->success('关闭成功');
    }


    /**
     * 首页
     *
     */
    public function aa()
    {
        $json = '{"code":"","room_no":"MXSC0016","pay_money":"118.00","pay_date":"20251015"}';
        $form_data = json_decode($json,true);
        $admin_id = $this->request->param('admin_id');
        $dbConfig = [
            'type'      => 'mysql',
            'hostname'  => '127.0.0.1',
            'database'  => 'nuanqi',
            'username'  => 'nuanqi',
            'password'  => 'ypLwydRdfmb8YKpe',
            'hostport'  => '3306',
        ];
        if(in_array($admin_id,[6])){
            // 创建连接并执行查询
            $result = Db::connect($dbConfig)
                ->name('fa_order_heat')
                ->where([
                    'house_number' => $form_data['room_no'],
                    'money' => $form_data['pay_money'],
                    'batch_num' => $form_data['pay_date'],
                    'pay_status' => 2,
                    'source' => '05',
                ])->find();
        }
        if(in_array($admin_id,[39])){
            // 创建连接并执行查询
            $result = Db::connect($dbConfig)
                ->name('fa_order')
                ->where([
                    'house_number' => $form_data['room_no'],
                    'pay_money' => $form_data['pay_money'],
                    'date' => $form_data['pay_date'],
                    'pay_status' => 2,
                    'source' => '05',
                ])->find();
        }
        if(!$result){
            $this->error('未查询到缴费，无法领取');
        }else{
            $this->success('查询成功',$result);
        }
    }
     
     
    public function index()
    {
        $this->success('请求成功');
    }
    
     public function other_mq()
    {
        $form_data = $this->request->param();
        if(isset($form_data['room_no'])){
            //暖气缴费，查询是否已缴费
            // 动态配置数据库连接
            $dbConfig = [
                'type'      => 'mysql',
                'hostname'  => '127.0.0.1',
                'database'  => 'nuanqi',
                'username'  => 'nuanqi',
                'password'  => 'ypLwydRdfmb8YKpe',
                'hostport'  => '3306',
            ];

            // 创建连接并执行查询
            $result = Db::connect($dbConfig)
                ->name('fa_order_heat')
                ->where([
                    'house_number' => $form_data['room_no'],
                    'money' => $form_data['pay_money'],
                    'batch_num' => $form_data['pay_date'],
                    'pay_status' => 2,
                ])->find();
            if(!$result){
                $this->error('未查询到缴费，无法领取');
            }
            $this->success('其它数据库链接成功',$result);
        }else{
            $this->success('未连接其它数据库');
        }
    }

    public function test()
    {
        $pay = new WechatPay();
        $data = $pay->lingqian([
            'appid'=>'wx22767416c55b1412',
            'out_bill_no' => 'aa202505061727',//必填 string(32)【商户单号】
            'transfer_scene_id' => '1000',//必填 string(36) 1000（现金营销），1006（企业报销）等
            'openid' => 'ohmKPv5lWNCSGudu0xDi3HaOexr8',//必填 string(64)
            'transfer_amount' => 20,//必填 integer【转账金额】 转账金额单位为“分”
            'transfer_remark' => '新会员有礼',//必填 string(32)【转账备注】
            'notify_url' => 'https://test.xinyaoan.com/api/index/index',//选填 string(256)【通知地址】
            'user_recv_perception'=>'现金奖励',
            //必填 array[object]
            'transfer_scene_report_infos' =>
                [
                    [
                        'info_type' => '活动名称',//必填 string(15)【信息类型】
                        'info_content' => '新人有礼',//必填 string(32)【信息内容】
                    ],
                    [
                        'info_type' => '奖励说明',//必填 string(15)【信息类型】
                        'info_content' => '新人抽奖一等奖',//必填 string(32)【信息内容】
                    ]
                ]
        ]);
        halt($data);
    }

    public function yanqian()
    {
        $aa = array (
            'accept' => '*/*',
            'host' => 'test.xinyaoan.com',
            'connection' => 'Keep-Alive',
            'pragma' => 'no-cache',
            'wechatpay-signature-type' => 'WECHATPAY2-SHA256-RSA2048',
            'wechatpay-signature' => 'Lsprdt65VNa6pfinLOmei6FtTqSh6xqYvpqT1LV4srrpQhz6O1pwDD8929EAb97NXwh5O0ESMLMlsYZfX6L91UErZth9E4mMXCjqNPIfk1rJq3vPbqg8a4OMku/x89mRilItgDCDrlqwzXiVWFaDl0iMwLGiA8DHTS9sMDjCCVTFfL5vehXagvaBjCXbnf4QNBF1mLP/vZek5KdmUQbScNJPRgEMNo0Wp1gu27WsZBMvIMrzuGU43BWdGgrcXcPUhNBIiFd/DOS5HGu7W4SLEd/AN9vkRlTPVAevFXbBIhDCKjg2HxVkvSdtKI6ndQJnuf+MOI4GDofyjIblz7uuvw==',
            'wechatpay-serial' => '60D7E29482EA84BB75F2B9E0A1728E38D3CA514F',
            'wechatpay-timestamp' => '1746780641',
            'wechatpay-nonce' => '9vvsBwIC5jcHT9IIXnK6uS2ZrmJ6wSRG',
            'content-type' => 'application/json',
            'user-agent' => 'Mozilla/4.0',
            'content-length' => '771',
        );
        $param =  array (
            'id' => 'fd148fac-f9ac-578f-845a-f75b86f67734',
            'create_time' => '2025-05-09T16:50:35+08:00',
            'resource_type' => 'encrypt-resource',
            'event_type' => 'MCHTRANSFER.BILL.FINISHED',
            'summary' => '商家转账单据终态通知',
            'resource' =>
                array (
                    'original_type' => 'mch_payment',
                    'algorithm' => 'AEAD_AES_256_GCM',
                    'ciphertext' => 'V/7e+QeWCwVeMgsRQeVtpkfuc72+IC4uhWkFhIjz/OcqhmnOTkp7jglMflnZZ6cjZ2vjlkXM8gQkDe+ynxzd37rsM6HADbwFmvgEnODQ6taWxDFM/E5Yli6eBptlWjYSjl/2nziwc1Q/YZxLvwqf1aAr7OPxy07QVGtcJuSZEY0jdADl5KJ50VKtPpmreLQe20+XvTWHB+N8HfE83W5OaVOau3XcJwBAkO5wWIs21YVucrNuwGFWela5Bf4Jd4SPq7WF/1EofPQjPsUufv9X4k446WEGpFPoxmrv0E6e4+ECUWaPAv16r9UD9dQaT/H+pR2Sbwr7SFIbr3OiK3eo14zD4l0srOiE9uTlHKt61MiN4gggABz8qjMfk3iWkPNznPpUePDXcPIXnC98o6XPnroo2nuJyjNELIQ=',
                    'associated_data' => 'mch_payment',
                    'nonce' => 'UPRXvr5kxfOV',
                ),
        );
        $inWechatpaySignature = 'Lsprdt65VNa6pfinLOmei6FtTqSh6xqYvpqT1LV4srrpQhz6O1pwDD8929EAb97NXwh5O0ESMLMlsYZfX6L91UErZth9E4mMXCjqNPIfk1rJq3vPbqg8a4OMku/x89mRilItgDCDrlqwzXiVWFaDl0iMwLGiA8DHTS9sMDjCCVTFfL5vehXagvaBjCXbnf4QNBF1mLP/vZek5KdmUQbScNJPRgEMNo0Wp1gu27WsZBMvIMrzuGU43BWdGgrcXcPUhNBIiFd/DOS5HGu7W4SLEd/AN9vkRlTPVAevFXbBIhDCKjg2HxVkvSdtKI6ndQJnuf+MOI4GDofyjIblz7uuvw==';// 请根据实际情况获取
        $inWechatpayTimestamp = '1746780641';// 请根据实际情况获取
        $inWechatpaySerial = '60D7E29482EA84BB75F2B9E0A1728E38D3CA514F';// 请根据实际情况获取
        $inWechatpayNonce = '9vvsBwIC5jcHT9IIXnK6uS2ZrmJ6wSRG';// 请根据实际情况获取
        $inBody = json_encode(array (
            'id' => 'fd148fac-f9ac-578f-845a-f75b86f67734',
            'create_time' => '2025-05-09T16:50:35+08:00',
            'resource_type' => 'encrypt-resource',
            'event_type' => 'MCHTRANSFER.BILL.FINISHED',
            'summary' => '商家转账单据终态通知',
            'resource' =>
                array (
                    'original_type' => 'mch_payment',
                    'algorithm' => 'AEAD_AES_256_GCM',
                    'ciphertext' => 'V/7e+QeWCwVeMgsRQeVtpkfuc72+IC4uhWkFhIjz/OcqhmnOTkp7jglMflnZZ6cjZ2vjlkXM8gQkDe+ynxzd37rsM6HADbwFmvgEnODQ6taWxDFM/E5Yli6eBptlWjYSjl/2nziwc1Q/YZxLvwqf1aAr7OPxy07QVGtcJuSZEY0jdADl5KJ50VKtPpmreLQe20+XvTWHB+N8HfE83W5OaVOau3XcJwBAkO5wWIs21YVucrNuwGFWela5Bf4Jd4SPq7WF/1EofPQjPsUufv9X4k446WEGpFPoxmrv0E6e4+ECUWaPAv16r9UD9dQaT/H+pR2Sbwr7SFIbr3OiK3eo14zD4l0srOiE9uTlHKt61MiN4gggABz8qjMfk3iWkPNznPpUePDXcPIXnC98o6XPnroo2nuJyjNELIQ=',
                    'associated_data' => 'mch_payment',
                    'nonce' => 'UPRXvr5kxfOV',
                ),
        ));// 请根据实际情况获取，例如: file_get_contents('php://input');
//halt($inBody);
        $apiv3Key = '7R2NxMMKdE4BKPZK5hXnaQ9BCw4zGehb';// 在商户平台上设置的APIv3密钥

// 根据通知的平台证书序列号，查询本地平台证书文件，
// 假定为 `/path/to/wechatpay/inWechatpaySerial.pem`
        $platformPublicKeyInstance = Rsa::from('-----BEGIN CERTIFICATE-----
MIIEKDCCAxCgAwIBAgIUHWSiZ59KaakUqaAYRh08t16kdgMwDQYJKoZIhvcNAQEL
BQAwXjELMAkGA1UEBhMCQ04xEzARBgNVBAoTClRlbnBheS5jb20xHTAbBgNVBAsT
FFRlbnBheS5jb20gQ0EgQ2VudGVyMRswGQYDVQQDExJUZW5wYXkuY29tIFJvb3Qg
Q0EwHhcNMjQwMTIyMDgwODU0WhcNMjkwMTIwMDgwODU0WjCBgTETMBEGA1UEAwwK
MTY2NDMwMTgxNDEbMBkGA1UECgwS5b6u5L+h5ZWG5oi357O757ufMS0wKwYDVQQL
DCTljZfpmLPmmajmmZ/kvZPogrLnlKjlk4HmnInpmZDlhazlj7gxCzAJBgNVBAYT
AkNOMREwDwYDVQQHDAhTaGVuWmhlbjCCASIwDQYJKoZIhvcNAQEBBQADggEPADCC
AQoCggEBALK3ENvymUu9wL6njdAf9V1V9x1k9V4JKRNI5H+qa1Xzf9rSTriYapVp
07cT8WvM4foXZy8DUDjZh0YGgsO9ZfLscIyxpFAq8J/X4VyBAVTCXnJfX+nex4Zd
O7vT2/u29yJcUTp70zmxKTPV+eGKWJ3v6l8y64w46ByTKmxm2DWmE46naf6i0NYI
0z4iBwQnsT7c9wjH13Oi4wK8GBRUzhXBORPTc50NVbdmUk6K1HMVOyQ1NOozMHp6
lJ6BF7zIYcLSz3TUyTP3k8KDd+sbceQfILRRinuoiwxTmcNiIGYlK/LILO5Lkj8z
0JJcxC98o8YX5l5cJ/zqLozOyaalPocCAwEAAaOBuTCBtjAJBgNVHRMEAjAAMAsG
A1UdDwQEAwID+DCBmwYDVR0fBIGTMIGQMIGNoIGKoIGHhoGEaHR0cDovL2V2Y2Eu
aXRydXMuY29tLmNuL3B1YmxpYy9pdHJ1c2NybD9DQT0xQkQ0MjIwRTUwREJDMDRC
MDZBRDM5NzU0OTg0NkMwMUMzRThFQkQyJnNnPUhBQ0M0NzFCNjU0MjJFMTJCMjdB
OUQzM0E4N0FEMUNERjU5MjZFMTQwMzcxMA0GCSqGSIb3DQEBCwUAA4IBAQAZfsuV
MFsZqWjXxYN3Yrv0OSFCBU+ObJv1Vczsnd5GzXZqWMB8rsB+505kbK8Su0UIucnQ
SpDiZZSTetgwcKd0R4Sz6kYNLADE1fEPGZNl2kcHoRtG2P7ZJsavyYGkxMPaAP42
geMX+6j8bj4nrVYH0GMYPfjYsRo5zgaTlzVj5IR9osRbNEhzz9KJilU8psQiD3gw
AefzExpdDVyqeuUDYt3f1fXKdrgtFK8o99+odLG5YwX6WDALdoooGnZFG/2HWhSM
n9NSDMFigOcJhCIzDoZt8aXsb5RFxNv2eWvZXNeB83mXi0Jtt3UFESwHKlsEesOf
ErcbQooRPP01Xg2H
-----END CERTIFICATE-----', Rsa::KEY_TYPE_PUBLIC);

        $verifiedStatus = Rsa::verify(
        // 构造验签名串
            Formatter::joinedByLineFeed($inWechatpayTimestamp, $inWechatpayNonce, $inBody),
            $inWechatpaySignature,
            '-----BEGIN CERTIFICATE-----
MIIEKDCCAxCgAwIBAgIUHWSiZ59KaakUqaAYRh08t16kdgMwDQYJKoZIhvcNAQEL
BQAwXjELMAkGA1UEBhMCQ04xEzARBgNVBAoTClRlbnBheS5jb20xHTAbBgNVBAsT
FFRlbnBheS5jb20gQ0EgQ2VudGVyMRswGQYDVQQDExJUZW5wYXkuY29tIFJvb3Qg
Q0EwHhcNMjQwMTIyMDgwODU0WhcNMjkwMTIwMDgwODU0WjCBgTETMBEGA1UEAwwK
MTY2NDMwMTgxNDEbMBkGA1U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FG/2HWhSM
n9NSDMFigOcJhCIzDoZt8aXsb5RFxNv2eWvZXNeB83mXi0Jtt3UFESwHKlsEesOf
ErcbQooRPP01Xg2H
-----END CERTIFICATE-----'
        );
        halt($verifiedStatus);
//        if ($timeOffsetStatus && $verifiedStatus) {
        // 转换通知的JSON文本消息为PHP Array数组
        $inBodyArray = (array)json_decode($inBody, true);
//            halt($inBodyArray);
        // 使用PHP7的数据解构语法，从Array中解构并赋值变量
        ['resource' => [
            'ciphertext'      => $ciphertext,
            'nonce'           => $nonce,
            'associated_data' => $aad
        ]] = $inBodyArray;
        // 加密文本消息解密
        $inBodyResource = AesGcm::decrypt($ciphertext, $apiv3Key, $nonce, $aad);
        // 把解密后的文本转换为PHP Array数组
        $inBodyResourceArray = (array)json_decode($inBodyResource, true);
        print_r($inBodyResourceArray);// 打印解密后的结果
//        }
    }

    public function aa1()
    {
        $aes = new AesUtil('7R2NxMMKdE4BKPZK5hXnaQ9BCw4zGehb');

        $a = $aes->decryptToString('mch_payment','UPRXvr5kxfOV','V/7e+QeWCwVeMgsRQeVtpkfuc72+IC4uhWkFhIjz/OcqhmnOTkp7jglMflnZZ6cjZ2vjlkXM8gQkDe+ynxzd37rsM6HADbwFmvgEnODQ6taWxDFM/E5Yli6eBptlWjYSjl/2nziwc1Q/YZxLvwqf1aAr7OPxy07QVGtcJuSZEY0jdADl5KJ50VKtPpmreLQe20+XvTWHB+N8HfE83W5OaVOau3XcJwBAkO5wWIs21YVucrNuwGFWela5Bf4Jd4SPq7WF/1EofPQjPsUufv9X4k446WEGpFPoxmrv0E6e4+ECUWaPAv16r9UD9dQaT/H+pR2Sbwr7SFIbr3OiK3eo14zD4l0srOiE9uTlHKt61MiN4gggABz8qjMfk3iWkPNznPpUePDXcPIXnC98o6XPnroo2nuJyjNELIQ=');
        halt(json_decode($a,true));
    }
}



class AesUtil {
    /**
     * AES key
     *
     * @var string
     */
    private $aesKey;
    const KEY_LENGTH_BYTE = 32;
    const AUTH_TAG_LENGTH_BYTE = 16;
    /**
     * Constructor
     */
    public
    function __construct($aesKey) {
        if (strlen($aesKey) != self::KEY_LENGTH_BYTE) {
            throw new InvalidArgumentException('无效的ApiV3Key，长度应为32个字节');
        }
        $this->aesKey = $aesKey;
    }
    /**
     * Decrypt AEAD_AES_256_GCM ciphertext
     *
     * @param string    $associatedData     AES GCM additional authentication data
     * @param string    $nonceStr           AES GCM nonce
     * @param string    $ciphertext         AES GCM cipher text
     *
     * @return string|bool      Decrypted string on success or FALSE on failure
     */
    public
    function decryptToString($associatedData, $nonceStr, $ciphertext) {
        $ciphertext = \base64_decode($ciphertext);
        if (strlen($ciphertext) <= self::AUTH_TAG_LENGTH_BYTE) {
            return false;
        }
        // ext-sodium (default installed on >= PHP 7.2)
        if (function_exists('\sodium_crypto_aead_aes256gcm_is_available') && \sodium_crypto_aead_aes256gcm_is_available()) {
            return \sodium_crypto_aead_aes256gcm_decrypt($ciphertext, $associatedData, $nonceStr, $this->aesKey);
        }
        // ext-libsodium (need install libsodium-php 1.x via pecl)
        if (function_exists('\Sodium\crypto_aead_aes256gcm_is_available') && \Sodium\crypto_aead_aes256gcm_is_available()) {
            return \Sodium\crypto_aead_aes256gcm_decrypt($ciphertext, $associatedData, $nonceStr, $this->aesKey);
        }
        // openssl (PHP >= 7.1 support AEAD)
        if (PHP_VERSION_ID >= 70100 && in_array('aes-256-gcm', \openssl_get_cipher_methods())) {
            $ctext = substr($ciphertext, 0, -self::AUTH_TAG_LENGTH_BYTE);
            $authTag = substr($ciphertext, -self::AUTH_TAG_LENGTH_BYTE);
            return \openssl_decrypt($ctext, 'aes-256-gcm', $this-> aesKey, \OPENSSL_RAW_DATA, $nonceStr,
                $authTag, $associatedData);
        }
        throw new \RuntimeException('AEAD_AES_256_GCM需要PHP 7.1以上或者安装libsodium-php');
    }
}
